﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace Ession
{
    /// <summary>
    /// 用于多线程传输文件
    /// </summary>
    public class MultiChunkTransfer
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fileNameAndPath"></param>
        /// <param name="chunks"></param>
        /// <param name="remoteEndPoint"></param>

        public MultiChunkTransfer(string fileNameAndPath, int chunks, IPEndPoint remoteEndPoint)
        {
            this.file = new FileInfo(fileNameAndPath);
            FileSize = (int)file.Length;
            chunkcount = chunks;
            this.remoteEndPoint = remoteEndPoint;
            Init();
        }

        public MultiChunkTransfer(string fileNameAndPath, int chunks, IPEndPoint remoteEndPoint, int threadCount)
        {
            Init();
        }

        public FileInfo file;
        public List<FileChunkInfo> fileChunks;//=new List<FileChunkInfo>();
        public int FileSize;
        public IPEndPoint remoteEndPoint;
        private int chunkcount = 1;

        private Thread[] threads;


        public void DivideFile(int chunkCount)
        {
            int persize = FileSize / chunkCount;
            fileChunks = new List<FileChunkInfo>();
            for (int i = 0; i < chunkCount - 1; i++)
            {
                fileChunks.Add(new FileChunkInfo(persize * i, persize));
            }
            fileChunks.Add(new FileChunkInfo(persize * (chunkCount - 1), FileSize - persize * (chunkCount - 1)));

        }


        public void SendFileThread()
        {
            TcpClient tc = new TcpClient(new IPEndPoint(IPAddress.Loopback,5556));
            try
            {
                tc.Connect(remoteEndPoint);
                if (tc.Connected)
                {
                    var data = new byte[1024];
                    int readCount = 0;
                    using (BinaryWriter bw = new BinaryWriter(tc.GetStream()))
                    {
                        using (BinaryReader br = new BinaryReader(File.OpenRead(file.FullName)))
                        {
                            do
                            {
                                readCount = br.Read(data, 0, data.Length);
                                bw.Write(data, 0, readCount);
                            } while (readCount > 0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

                throw;
            }


        }

        //1.文件分块
        //2.建立连接准备
        private void Init()
        {
            //1.
            DivideFile(chunkcount);

            //2.

        }
    }
}
